package Managers;

/*
 * THE CODE CONTAINED INSIDE THIS FILE FROM HERE IN WAS TAKEN FROM
 * http://stackoverflow.com/questions/2064066/does-java-have-built-in-libraries-for-audio-synthesis/2065693#2065693
 * THE CODE WAS HEAVILLY ADAPTED TO MEET OUR NEEDS. 
 */

import java.util.Timer;
import java.util.TimerTask;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

import calendar.GlobalSettings;

public class Tone
{	    
	private static Timer timer = null;
	private static boolean playable = true;
    public static void playTone(int n)
    {
    	if(GlobalSettings.audio_mode && playable)
    	{
    		playable = false;
    		//being honest i don't really understand this code i know it works
    		//and i know that depending on the value of n  depends on the pitch/frequency
    		//it plays.
	    	n += 10;
	    	int sample_rate = 16*1024; //16khz
	    	int length = sample_rate * 45/ 1000;
	    	byte[] sin = new byte[2 * sample_rate];
			double exp = ((double) n - 1) / 12d;
		    double f = 440d * Math.pow(2d, exp);
		    
		    for (int i = 0; i < sin.length; i++)
		    {
		        double period = (double)sample_rate / f;
		        double angle = 2.0 * Math.PI * i / period;
		        sin[i] = (byte)(Math.sin(angle) * 127f);
		    }
	    	
	    	final AudioFormat af = new AudioFormat(sample_rate, 8, 1, true, true);
	        
	    	SourceDataLine line;
			
	        try
			{
				line = AudioSystem.getSourceDataLine(af);
				line.open(af, sample_rate);
		        line.start();
		        
		        line.write(sin, 0, length);
		      
		        line.drain();
		        line.close();
			}
			catch (LineUnavailableException e)
			{
				//fail silently
			}
			finally
			{
				 if(timer == null){ timer = new Timer(); }
				 
				 timer.scheduleAtFixedRate(new TimerTask(){
	            		int i = 3;
	                public void run() {
	                	i--;
	                    if ( i< 0)
	                    {
	                        timer.cancel();
	                        timer = null;
	                        playable = true;
	                    }	                
	                }
	            }, 0, 50);
			}
    	}
    }
}
